package com.zyz.common.aspect;

import com.zyz.common.exception.InvalidParamException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;

/**
 * controller注解校验
 */
@Aspect
@Component
public class ValidationAspect {
    private final static String el = "@annotation(org.springframework.web.bind.annotation.RequestMapping)";

    @Before(ValidationAspect.el)
    public void before() {
    }

    @Around(ValidationAspect.el)
    public Object around(ProceedingJoinPoint p) throws Throwable {
        Object[] args = p.getArgs();
        for (Object arg : args) {
            if (arg instanceof BindingResult) {
                BindingResult bindingResult = (BindingResult) arg;
                if (bindingResult.hasErrors()) {
                    throw new InvalidParamException(bindingResult.getFieldError().getField(),
                            bindingResult.getFieldError().getDefaultMessage());
                }
            }
        }
        return p.proceed();
    }

    @After(ValidationAspect.el)
    public void after() {
    }
}
